package com.bbm.communitysystem.controller;

import cn.hutool.core.bean.BeanUtil;
import com.bbm.communitysystem.core.Token;
import com.bbm.communitysystem.core.domain.Captcha;
import com.bbm.communitysystem.core.domain.Decryption;
import com.bbm.communitysystem.core.domain.R;
import com.bbm.communitysystem.core.redis.Redis;
import com.bbm.communitysystem.domain.UserCred;
import com.bbm.communitysystem.domain.UserInfo;
import com.bbm.communitysystem.domain.bo.HouseholdBo;
import com.bbm.communitysystem.domain.bo.UserCredBo;
import com.bbm.communitysystem.domain.dto.FamilyDto;
import com.bbm.communitysystem.domain.dto.UserCredDto;
import com.bbm.communitysystem.domain.dto.UserInfoDto;
import com.bbm.communitysystem.domain.vo.LoginPageVo;
import com.bbm.communitysystem.domain.vo.RegisterPageVo;
import com.bbm.communitysystem.service.IFamilyService;
import com.bbm.communitysystem.service.IUserCredService;
import com.bbm.communitysystem.service.IUserInfoService;
import com.bbm.communitysystem.service.impl.HouseholdServiceImpl;
import com.bbm.communitysystem.tools.ImgCaptcha;
import com.bbm.communitysystem.tools.SHA256;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletRequest;
import lombok.RequiredArgsConstructor;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

@Tag(name = "登录控制器")
@RestController
@RequestMapping("/userCred")
@RequiredArgsConstructor
public class UserCredController {

    private final IUserCredService userCredService;

    private final IUserInfoService userInfoService;

    private final IFamilyService familyService;

    private final HouseholdServiceImpl householdService;

    private final Redis redis;

    private final Token token;




    @PostMapping("/register")
    @Transactional(rollbackFor = Exception.class)
    public R<RegisterPageVo> register(HttpServletRequest request, @RequestBody UserCredDto userCredDto) {

        String code = redis.getValue(request.getLocalAddr() + "_" + userCredDto.getCaptchaKey()) + "";
        if (code.equals("null") || code.isEmpty()) {
            return R.error("验证码错误");
        }


        UserCred one = userCredService.lambdaQuery()
                .eq(UserCred::getUserName, userCredDto.getUserName())
                .one();
        if (one != null) {
            return R.error("用户名已存在");
        }

        //创建用户凭据
        UserCredDto userCredDto1 = userCredService.registerUserCredDto(BeanUtil.copyProperties(userCredDto, UserCredBo.class));

        //创建用户信息
        UserInfoDto userInfoDto = userInfoService.CreateUserInfo(BeanUtil.copyProperties(userCredDto1, UserCredBo.class));

        //创建用户家庭
        FamilyDto familyDto = new FamilyDto();
        familyDto.setFamilyName(userCredDto1.getUserName() + "的家庭");
        familyDto.setUpdateBy(userInfoDto.getId() + "");
        FamilyDto family = familyService.createFamily(familyDto);

        if (family == null) {
            throw new RuntimeException("创建家庭失败");
        }

        //创建用户住户信息
        HouseholdBo householdBo = new HouseholdBo();
        householdBo.setFamilyId(family.getId());
        householdBo.setUserId(userInfoDto.getId());
        householdBo.setUpdateTime(System.currentTimeMillis() + "");
        householdBo.setUpdateBy(userInfoDto.getId() + "");
        int household = householdService.createHousehold(householdBo);

        if (household == 0) {
            throw new RuntimeException("创建住户信息失败");
        }

        String createdToken = token.CreateToken(userCredDto1);

        RegisterPageVo registerPageVo = new RegisterPageVo();

        if (userCredDto.getIsAUTO()){
            registerPageVo.setAuth(userCredDto.getPassword());
        }

        registerPageVo.setId(userInfoDto.getId());
        registerPageVo.setToken(createdToken);

        return R.ok("注册成功", registerPageVo);
    }


    @GetMapping("/getCaptcha")
    public R<String> getCaptcha(HttpServletRequest request) {
        Captcha captcha = ImgCaptcha.generateCaptcha();
        redis.setValue(request.getLocalAddr() + "_" + captcha.getKey(), captcha.getCode(), 10);

        return R.ok("获取成功", captcha.getImg());
    }


    @PostMapping("/login")
    public R<LoginPageVo> login(@RequestBody UserCredDto userCredDto) {

        UserCred one = userCredService.lambdaQuery()
                .eq(UserCred::getUserName, userCredDto.getUserName())
                .one();

        if (one == null) {
            return R.error("用户不存在");
        }

        UserCred one1 = userCredService.lambdaQuery()
                .eq(UserCred::getUserName, userCredDto.getUserName())
                .one();
        if (one1 == null) {
            return R.error("用户名不存在");
        }

        Decryption decryption = SHA256.decryption(one1.getPassword());

        if (!SHA256.verify(userCredDto.getPassword(), decryption)) {
            return R.error("密码错误");
        }

        UserInfo one2 = userInfoService.lambdaQuery()
                .eq(UserInfo::getCredId, one1.getId())
                .one();

        LoginPageVo loginPageVo = new LoginPageVo();

        if (userCredDto.getIsAUTO()){
            loginPageVo.setAuth(userCredDto.getPassword());
        }

        userCredDto.setId(one2.getId());

        loginPageVo.setId(one2.getId());
        loginPageVo.setToken(token.CreateToken(userCredDto));


        return R.ok("登录成功", loginPageVo);
    }



}
